package org.example.controller;

import org.example.domain.User;
import org.example.util.JDBCUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet(value = "/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");//设置request编码
        resp.setContentType("text/html;charset=utf-8");//设置response 编码
        String username = req.getParameter("username");//获取表单用户名
        String password = req.getParameter("password");//获取表单密码

        if ("".equals(username) || username == null || "".equals(password) || password == null) {
            req.setAttribute("msg", "用户姓名不能为空！请重新输入用户名密码!");
            req.getRequestDispatcher("login.jsp").forward(req, resp);
            return;
        }

        Connection connection= JDBCUtil.getConnection();
        String sql="select id,username,password from user where username = ?";

        PreparedStatement stmt=null;
        ResultSet rs=null;
        User user = new User();
        try {
            stmt=connection.prepareStatement(sql);
            stmt.setString(1,username);
            rs=stmt.executeQuery();
            if (rs.next()) {
                user.setId(rs.getLong("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtil.closeAll(rs,stmt,connection);
        }

        if (user!=null && (user.getUsername().equals(username) && user.getPassword().equals(password))) {
            req.getSession().setAttribute("username", username);
            resp.sendRedirect("index.jsp");
        }else {
            req.getSession().setAttribute("msg", "登录失败，账号或密码错误！");
            resp.sendRedirect("fail.jsp");
            return;
        }
    }
}
